﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sector7.Framework.Core;
using Sector7.Framework.Enums;
using Sector7.Medical.Biz;
using Sector7.Medical.Consts;
using Sector7.Framework.Utility;
using Sector7.Medical.EntityType;

namespace Sector7.Medical.INFM.Controls
{
    /// <summary>
    /// DepartmentSummaryControl.xaml 的交互逻辑
    /// </summary>
    public partial class DepartmentSummaryControl : AddModeControlBase
    {
        #region Accessor

        /// <summary>
        /// 科室信息
        /// </summary>
        private M7_Department Department
        {
            get { return m_entity as M7_Department; }
            set { m_entity = value; }
        }
        #endregion

        #region Public functions
        #endregion

        #region Private functions

        /// <summary>
        /// Control Loaded
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DepartmentSummaryControl_Loaded(object sender, RoutedEventArgs e)
        {
            m_crud = CrudType.Unknown;

            Senvironments.ProgressWindow.Visibility = Visibility.Visible;

            SwitchPropertiyGroupsEnabledState(false);
            SwitchPropertiyActionButtonsState(CrudType.Unknown);
            SwitchActionButtonsState(false);

            var worker = BackgroundWorkerUtil.GetWorker(this);
            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(LoadData_DoWork);
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 加载数据工作线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadData_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            GetData();

            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadData));
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        private new void GetData()
        {
            m_deptList = Agent_INFS.GetDepartmentList(C_DepartmentFlags.DEPARTMENT);
            m_tempDeptList.AddRange(m_deptList.ToArray());
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            ClientUtil.LoadItemsSource(dtgMain, m_deptList);

            SwitchPropertiyActionButtonsStateByDataCount();

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// 清空界面输入信息
        /// </summary>
        private void ClearDepartmentPropertiye()
        {
            txbDeptId.Text = "";
            txbDeptName.Text = "";
            txbSpellCode.Text = "";
            txbRemarks.Text = "";
            ckbIsValid.IsChecked = true;
            ckbCanRegistry.IsChecked = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isEnabled"></param>
        private void SwitchPropertiyGroupsEnabledState(bool isEnabled)
        {
            txbDeptId.IsEnabled = false;
            txbDeptName.IsEnabled = isEnabled;
            txbSpellCode.IsEnabled = isEnabled;
            txbRemarks.IsEnabled = isEnabled;
            ckbIsValid.IsEnabled = isEnabled;
            ckbCanRegistry.IsEnabled = isEnabled;
            ckbCanCharge.IsEnabled = !(bool)(ckbCanRegistry.IsChecked);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="crud"></param>
        private void SwitchPropertiyActionButtonsState(CrudType crud)
        {
            switch (crud)
            {
                case CrudType.Create:
                    btnAdd.IsEnabled = true;
                    btnModify.IsEnabled = false;
                    btnDelete.IsEnabled = false;
                    break;
                case CrudType.Read:
                    btnAdd.IsEnabled = true;
                    btnModify.IsEnabled = true;
                    btnDelete.IsEnabled = true;
                    break;
                default:
                    btnAdd.IsEnabled = false;
                    btnModify.IsEnabled = false;
                    btnDelete.IsEnabled = false;
                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isVisibility"></param>
        private void SwitchActionButtonsState(bool isVisibility)
        {
            Visibility visibility = isVisibility ? Visibility.Visible : Visibility.Hidden;
            btnOk.Visibility = visibility;
            btnCancel.Visibility = visibility;

            btnAdd.IsEnabled = !isVisibility;
            btnModify.IsEnabled = !isVisibility;
            btnDelete.IsEnabled = !isVisibility;
        }

        /// <summary>
        /// 
        /// </summary>
        private void SwitchPropertiyActionButtonsStateByDataCount()
        {
            if (m_deptList.Count == 0)
            {
                SwitchPropertiyActionButtonsState(CrudType.Create);
                ClearDepartmentPropertiye();
            }
            else
            {
                SwitchPropertiyActionButtonsState(CrudType.Read);
            }
        }

        /// <summary>
        /// 生成拼音码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSpellCode_Click(object sender, RoutedEventArgs e)
        {
            txbSpellCode.Text = CharacterUtil.GetSpellCodeString(txbDeptName.Text.Trim());
        }

        /// <summary>
        /// 操作成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DepartmentSummaryControl_AddSuccess(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 数据表选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dtgMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_Department)
            {
                SwitchPropertiyActionButtonsState(CrudType.Read);

                M7_Department department = dtgMain.SelectedItem as M7_Department;
                ShowDepartmentInfor(department);
            }
            else
            {
                SwitchPropertiyGroupsEnabledState(false);
                SwitchActionButtonsState(false);
                SwitchPropertiyActionButtonsStateByDataCount();
                ClearDepartmentPropertiye();
            }
        }

        /// <summary>
        /// 显示DepartmentInfor
        /// </summary>
        /// <param name="department"></param>
        private void ShowDepartmentInfor(M7_Department department)
        {
            this.txbDeptId.Text = department.DeptId.ToString();
            this.txbDeptName.Text = department.DeptName;
            this.txbRemarks.Text = department.Remarks;
            this.txbSpellCode.Text = department.SpellCode;
            this.ckbIsValid.IsChecked = department.IsValid;
            this.ckbCanRegistry.IsChecked = (department.Flags & C_DepartmentFlags.CAN_REGISTRY) == C_DepartmentFlags.CAN_REGISTRY ? true : false;
            ckbCanCharge.IsChecked = (department.Flags & C_DepartmentFlags.CAN_CHARGE) == C_DepartmentFlags.CAN_CHARGE ? true : false;
        }

        /// <summary>
        /// Check Data
        /// </summary>
        /// <returns></returns>
        protected override bool CheckData()
        {
            m_errors.Clear();

            string departmentName = txbDeptName.Text.Trim();
            string spellCode = txbSpellCode.Text.Trim();
            string remarks = txbRemarks.Text.Trim();
            bool isValid = (bool)ckbIsValid.IsChecked;
            bool canRegistry = (bool)ckbCanRegistry.IsChecked;
            bool canCharge = (bool)ckbCanCharge.IsChecked;

            if (string.IsNullOrEmpty(departmentName))
            {
                m_errors.Add("一级科室名称", "不能为空!");
            }
            if (string.IsNullOrEmpty(spellCode))
            {
                m_errors.Add("拼音码", "不能为空!");
            }

            if (m_errors.Count == 0)
            {
                if (this.Crud == CrudType.Create)
                {
                    Department = new M7_Department();
                }
                Department.DeptName = departmentName;
                Department.SpellCode = spellCode;
                Department.Remarks = remarks;
                Department.IsValid = isValid;
                Department.Flags = C_DepartmentFlags.DEPARTMENT;
                if (canRegistry)
                {
                    Department.Flags |= C_DepartmentFlags.CAN_REGISTRY;
                }
                if (canCharge)
                {
                    Department.Flags |= C_DepartmentFlags.CAN_CHARGE;
                }
            }
            return base.CheckData();
        }

        /// <summary>
        /// Add Data
        /// </summary>
        protected override void AddData()
        {
            switch (m_crud)
            {
                case CrudType.Create:
                    object departmentIdObj = Agent_INFS.AddDepartment(Department);
                    if (departmentIdObj != null)
                    {
                        Department.DeptId = Convert.ToInt32(departmentIdObj);
                        m_deptList.Add(Department);
                        m_tempDeptList.Add(Department);
                        dtgMain.Items.Refresh();
                        SelectDepartmentItem(Department);
                    }
                    SwitchPropertiyGroupsEnabledState(false);
                    SwitchActionButtonsState(false);
                    break;
                case CrudType.Update:
                    bool isChanged = false;
                    var delta = GetDelta(C_ColumnName.DEPT_ID, ref isChanged);
                    if (isChanged)
                    {
                        int result = Agent_INFS.UpdateDepartment(delta);
                        if (result == 1)
                        {
                            int flags = C_DepartmentFlags.SUB_DEPARTMENT;
                            if ((Department.Flags & C_DepartmentFlags.CAN_REGISTRY) == C_DepartmentFlags.CAN_REGISTRY)
                            {
                                flags = flags | C_DepartmentFlags.CAN_REGISTRY;
                            }
                            Agent_INFS.UpdateSubDepartmentFlags(Department.DeptId, flags);

                            dtgMain.Items.Refresh();
                        }
                    }
                    SwitchPropertiyGroupsEnabledState(false);
                    SwitchActionButtonsState(false);
                    break;
                default:
                    break;
            }

            base.AddData();
        }

        /// <summary>
        /// 选中Item
        /// </summary>
        /// <param name="department"></param>
        private void SelectDepartmentItem(M7_Department department)
        {
            if (dtgMain.Items.Contains(department))
            {
                dtgMain.SelectedItem = department;
            }
        }

        /// <summary>
        /// 初始化窗口
        /// </summary>
        /// <param name="crud">窗口操作类型</param>
        public void InitializeControl(CrudType crud)
        {
            m_crud = crud;

            string prefix = string.Empty;
            switch (m_crud)
            {
                case CrudType.Create:
                    prefix = "新建";
                    InitializeForCreating();
                    break;
                case CrudType.Update:
                    prefix = "修改";
                    InitializeForUpdating();
                    break;
                default:
                    break;
            }

            InitializeForOthers();

            this.Tag = string.Format("{0}{1}", prefix, this.Tag);

            this.DataContext = m_entity;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            InitializeControl(CrudType.Create);
        }

        /// <summary>
        /// 初始化添加
        /// </summary>
        protected override void InitializeForCreating()
        {
            SwitchPropertiyGroupsEnabledState(true);
            SwitchActionButtonsState(true);
            ClearDepartmentPropertiye();

            base.InitializeForCreating();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnModify_Click(object sender, RoutedEventArgs e)
        {
            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_Department)
            {
                var department = dtgMain.SelectedItem as M7_Department;
                Department = department;
                InitializeControl(CrudType.Update);
            }
        }

        /// <summary>
        /// 初始化修改
        /// </summary>
        protected override void InitializeForUpdating()
        {
            SwitchPropertiyGroupsEnabledState(true);
            SwitchActionButtonsState(true);
            ShowDepartmentInfor(Department);

            base.InitializeForUpdating();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (dtgMain.SelectedItem is M7_Department)
            {
                MessageBoxResult mbr = Alert.ShowDialog(AlertType.Question, "是否确定删除该一级科室");
                if (mbr == MessageBoxResult.Yes)
                {
                    M7_Department department = dtgMain.SelectedItem as M7_Department;
                    int ret = Agent_INFS.DeleteDepartment(department.DeptId);
                    if (ret > 0)
                    {
                        if (m_deptList.Contains(department))
                        {
                            int index = dtgMain.Items.IndexOf(department);
                            index++;

                            m_deptList.Remove(department);
                            dtgMain.Items.Refresh();

                            if (dtgMain.Items.Count != 0)
                            {
                                while (index >= dtgMain.Items.Count)
                                {
                                    index--;
                                }
                                dtgMain.SelectedIndex = index;
                            }
                        }

                        if (m_tempDeptList.Contains(department))
                        {
                            m_tempDeptList.Remove(department);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 确定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            if (CheckData())
            {
                AddData();
            }
            else
            {
                ShowErrors();
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            SwitchPropertiyGroupsEnabledState(false);
            SwitchActionButtonsState(false);

            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_Department)
            {
                M7_Department department = dtgMain.SelectedItem as M7_Department;
                ShowDepartmentInfor(department);
            }

            m_crud = CrudType.Unknown;
        }

        /// <summary>
        ///  Search关键值改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchBox_KeywordsChanging(object sender, KeyEventArgs e)
        {
            string keywords = searchBox.Keywords;
            m_deptList = m_tempDeptList.FindAll(delegate(M7_Department __department)
            {
                if (__department.DeptId.ToString().Contains(keywords) ||
                    __department.DeptName.Contains(keywords))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
            ClientUtil.LoadItemsSource(dtgMain, m_deptList);
        }

        /// <summary>
        /// Search关键值重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchBox_KeywordsReset(object sender, EventArgs e)
        {
            m_deptList.Clear();
            m_deptList.AddRange(m_tempDeptList.ToArray());

            ClientUtil.LoadItemsSource(dtgMain, m_deptList);
        }

        /// <summary>
        /// 能否挂号Checked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ckbCanRegistry_Checked(object sender, RoutedEventArgs e)
        {
            ckbCanCharge.IsChecked = true;
            ckbCanCharge.IsEnabled = false;
        }

        /// <summary>
        /// 能否挂号UnChecked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ckbCanRegistry_Unchecked(object sender, RoutedEventArgs e)
        {
            ckbCanCharge.IsEnabled = true;
        }
        #endregion

        #region Structure

        /// <summary>
        /// 构造方法
        /// </summary>
        public DepartmentSummaryControl()
        {
            InitializeComponent();
        }

        #endregion

        #region Inner members

        /// <summary>
        /// 一级科室信息列表
        /// </summary>
        private List<M7_Department> m_deptList;

        /// <summary>
        /// 一级科室信息临时列表
        /// </summary>
        private List<M7_Department> m_tempDeptList = new List<M7_Department>();
        #endregion
    }
}
